package com.fxc.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class MyZuulFilter extends ZuulFilter {

    Logger logger = LoggerFactory.getLogger(MyZuulFilter.class);

    // 判断当前请求是否要进行过滤
    // 要过滤：返回true，继续执行run()方法
    // 不过滤：返回false，直接放行
    @Override
    public String filterType() {

        // 返回当前过滤器类型，决定当前过滤器在什么时候执行
        // pre表示在目标微服务前执行
        String filterType = "pre";

        return filterType;
    }

    /**
     * 还必须为筛选器定义filterOrder（）。如果优先级对筛选器不重要，则筛选器可能具有相同的筛选器顺序。过滤器顺序不需要是连续的。
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {

        // 获取RequestContext对象
        RequestContext requestContext = RequestContext.getCurrentContext();

        // 获取Request对象
        HttpServletRequest request = requestContext.getRequest();

        String parameter = request.getParameter("signal");

        return "hello".equals(parameter);
    }

    /**
     * if shouldFilter() is true, this method will be invoked. this method is the core method of a ZuulFilter
     *
     * @return Some arbitrary artifact may be returned. Current implementation ignores it.
     * @throws ZuulException if an error occurs during execution.
     */
    @Override
    public Object run() throws ZuulException {

        logger.info("当前请求过滤了，run方法执行了");

        // Current implementation ignores it.
        // 当前的实现会忽略这个方法的返回值，所以返回null，不做特殊处理
        return null;
    }
}
